<?php

class Application_Model_UserMapper {
	
	protected $_connection;
	
	public function __construct() {
		$this->_connection = new Application_Model_DbTable_User();
	}
	
	public function add(Application_Model_User $user) {
	
		$dbdata = array(
				'name' 		=> $user->getName(),
				'surname'	=> $user->getSurname(),
				'username'	=> $user->getUsername(),
				'password'	=> $user->getPassword(),
				'email'		=> $user->getEmail(),
				'userrole'	=> $user->getUserrole());
		$this->_connection->insert($dbdata);
	}
	
	public function fetchAll() {
			
		$entries = array();
		$result = $this->_connection->fetchAll();
			
		foreach($result as $row) {
			$user = new Application_Model_User();
	
			$user->setSurname($row->surname);
			$user->setName($row->name);
			$user->setUsername($row->username);
			$user->setId($row->id);
			$user->setEmail($row->email);
			$user->setUserrole($row->userrole);
	
			$entries[] = $user;
	
		}
		return $entries;
	}
	
	public function find($userId) {
	
		$resultRow = $this->_connection->fetchRow('id='.$userId)->toArray();
	
		return $resultRow;
	}
	
	
	public function updatePassword($data) {
	
		$this->_connection->update(array('password' => md5($data['password'])), 'id='.$data['id']);
	}
	
	public function edit(Application_Model_User $user) {
	
		$dbdata = array(
				'name' 		=> $user->getName(),
				'surname'	=> $user->getSurname(),
				'username'	=> $user->getUsername(),
				'email'		=> $user->getEmail(),
				'userrole'	=> $user->getUserrole());
		$this->_connection->update($dbdata, 'id='.$user->getId());
			
	}
}